package com.xingxing.sqlSession;

import com.xingxing.config.BoundSql;
import com.xingxing.pojo.Configuration;
import com.xingxing.pojo.MapperdStatement;
import com.xingxing.util.CamelUnderlineUtil;
import com.xingxing.util.GenericTokenParser;
import com.xingxing.util.ParameterMapping;
import com.xingxing.util.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: IPersistence_test
 * @description:
 * @author: xinghaozhao
 * @create: 2020-09-13
 */
public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MapperdStatement mapperdStatement, Object... params) throws Exception {
        // 1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取SQL语句 select * from custom where id = #{id} and username =#{username}
        //   转换SQL语句 select * from custom where id = ? and username = ?, 在此过程中还需对#{}中的值进行解析存储
        String sql = mapperdStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4.设置参数
        //获取参数的全路径
        String paramterType = mapperdStatement.getParamterType();

        Class<?> paramterTypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);

            // 从#{}中解析出来的参数名称
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);

            // 暴力访问
            declaredField.setAccessible(true);

            // 从params 对象中获取对应content的属性值
            Object o = declaredField.get(params[0]);

            // 为预处理对象中的参数赋值
            preparedStatement.setObject(i + 1, o);
        }
        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        // 6.封装返回结果集

        String resultType = mapperdStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        Method methods[] = resultTypeClass.getMethods();

        ArrayList<Object> objects = new ArrayList<>();

        while (resultSet.next()) {

            // 获取对应 bean的实例对象
            Object o = resultTypeClass.newInstance();

            //得到结果集元数据
            ResultSetMetaData metaData = resultSet.getMetaData();

            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);

                //得到别名后 可以得到这个列的bean的set方法
                String methodName = "set" + CamelUnderlineUtil.underlineToCamel(columnName);

                // 字段值
                Object value = resultSet.getObject(columnName);

                for (Method method : methods) {
                    //若有和这个列的set方法相同的方法
                    if (method.getName().equals(methodName)) {
                        //将数据库查出来的这个列的值赋值给这个bean
                        method.invoke(o, value);
                    }
                }

                // 使用反射或者内省，根据数据库表和实体类的对应关系，完成返回结果集的封装
//                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultTypeClass);
//                Method writeMethod = propertyDescriptor.getWriteMethod();
//
//                writeMethod.invoke(o,value);
            }
            objects.add(o);
        }
        return (List<E>) objects;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    /**
     * 完成对#{} 的解析工作：1、将#{} 用？代替  2、将#{}中解析出得值进行存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类：配合标记解析器完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();

        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        //解析出的sql语句
        String parseSql = genericTokenParser.parse(sql);

        //#{}中解析出的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);

        return boundSql;

    }
}
